import streamlit as st
import utills
import os
import subprocess
from streamlit_card import card
import time
import extra_streamlit_components as stx
from annotated_text import annotated_text
st.set_page_config(layout="wide")

upload_folder = "./upload/video_input/"
landmarks_folder = "./landmarks"
visualize_folder = "./visualize"


if "Page3uploadState" not in st.session_state:
    st.session_state.Page3uploadState = "Unupload"
if "PhotoState" not in st.session_state:
    st.session_state.PhotoState = "none"
upload_folder = "./upload/images"

def clear_folder(folder_path):
    # 获取文件夹中的所有文件和子文件夹
    files = os.listdir(folder_path)
    if not files:  # 如果文件夹为空
        return "文件夹内无文件"
    for file in files:
        # 构建文件/文件夹的完整路径
        file_path = os.path.join(folder_path, file)
        # 如果是文件，则删除
        if os.path.isfile(file_path):
            os.remove(file_path)
        # 如果是文件夹，则递归清空
        elif os.path.isdir(file_path):
            clear_folder(file_path)


with st.sidebar: 
    st.header("图像深度伪造检测模块")
    st.markdown("_基于图像噪声指纹提取＋跨模态融合架构的图像异常特征检测模块_")
    annotated_text(
        ("real ","真","#42CF52")
    )
    annotated_text(
        ("doubt ","存疑","#F7E62F")
    )
    annotated_text(
        ("fake ","假","#F0275E")
    )
    annotated_text(
        ("伪造指数","该值越高我们越趋向于目标为假","#23ACF0")
    )

    
headCol = st.columns([1,1,1])
with headCol[1]:
     image_url = ""
     stx.bouncing_image(image_source=image_url, animate=False, animation_time=1500, height=200, width=250)


Buttoncontainer = st.container()

with Buttoncontainer:
    ButtonCol = st.columns([3,2,2])

    with ButtonCol[1]:
        st.write("")
        mybutton = st.button("清除残余文件")
        if mybutton:
            folder_path = "./upload/video_input"  # 替换为您要清空的文件夹路径
            #清空视频输入
            clear_folder(folder_path)
            #清空landmark
            clear_folder(landmarks_folder)
            #清空visualize
            clear_folder(visualize_folder)
            st.session_state.uploadState = "Unupload"
            clear_folder("./upload")

            images_folder_path = "./upload/images"  # 替换为您要清空的文件夹路径
            #清空page2图片输入
            clear_folder(images_folder_path)
            st.session_state.Page3uploadState = "Unupload"
            st.success("文件夹已清空！")
            st.session_state.VideoState = "none"
            st.session_state.PhotoState = "none"
            st.session_state.mainState = "Unupload"
            st.session_state.WelcomeState = "Unupload"
            if os.path.exists("/home/xinan-works/complex_layout_example.pdf"):
                os.remove("/home/xinan-works/complex_layout_example.pdf")
                print(f"文件 pdf 删除成功")
            else:
                print("文件不存在，无法删除")



mainCol = st.columns([6,1])
with mainCol[0]:
    uploaded_file = st.file_uploader("")
    uploaded_filename = None  # 初始化变量用于存储上传文件的文件名

    # 如果有文件被上传
    if uploaded_file is not None:
        # 将文件保存到指定路径
        file_path = os.path.join(upload_folder, uploaded_file.name)
        with open(file_path, "wb") as f:
            f.write(uploaded_file.getbuffer())
        
        # 存储上传文件的文件名
        uploaded_filename = uploaded_file.name
        st.session_state.Page3uploadState = "uploaded"

emoji_col = st.columns([4,4,4])
if st.session_state.Page3uploadState == "Unupload":
    with emoji_col[1]:
        st.header("☝️🙄先上传图片哦")
if st.session_state.Page3uploadState == "uploaded":
    with emoji_col[1]:
        st.header("🫵😎图片上传成功")


    
if st.session_state.Page3uploadState == "uploaded":
    ProgressContainer =  st.empty()
    with ProgressContainer:
        bar=st.progress(0)
        #进度条
        for i in range(80):
            bar.progress(i+1)
            time.sleep(0.1)
    score = utills.trufor(f"./upload/images/{uploaded_file.name}")
    with open("/home/xinan-works/truefor_num.txt","w") as file:
        file.write(f"{score}"[0:-1])
    ProgressContainer.empty()
    if score>0.55:
        st.session_state.PhotoState = "fake"
    elif  0.5>= score>0.45:
        st.session_state.PhotoState = "doubt"
    else :
        st.session_state.PhotoState = "real"
    if st.session_state.PhotoState == "fake":
        res = card(
                title="Fake !!!!!!😡",
                text="看起来这是一个伪造的对象",
                image="https://www.zfuhao.com/upload/image/2022/1642085446656393.jpg",
                styles={
                    "card": {
                        "width": "450px",
                        "height": "300px",
                        "border-radius": "60px",
                        "box-shadow": "0 0 10px rgba(234,0,0,0.5)",
                        "background-color": "rgba(234, 0, 0, 0)"
                    },
                    "text": {
                        "font-family": "serif",
                    },
                    "filter": {
                        "background-color": "rgba(234, 0, 0, 0)"  # <- make the image not dimmed anymore
                    }
                }
            )
    if st.session_state.PhotoState == "real":
        res = card(
                title="Wow",
                text="🙂好像没有伪造痕迹哦",
                image="https://gd-hbimg.huaban.com/51da9549e3377a5287671a92aace8f7b534546e2d30-i7ZEfU_fw658",
                styles={
                    "card": {
                        "width": "450px",
                        "height": "300px",
                        "border-radius": "60px",
                        "box-shadow": "0 0 10px rgba(234,0,0,0.5)",
                        "background-color": "rgba(234, 0, 0, 0)"
                    },
                    "text": {
                        "font-family": "serif",
                    },
                    "filter": {
                        "background-color": "rgba(234, 0, 0, 0)"  # <- make the image not dimmed anymore
                    }
                }
            )
    if st.session_state.PhotoState == "doubt":
        res = card(
        title="Ooops ？！🤔",
        text="有点可疑，但是又有点不可疑",
        image="https://ts1.cn.mm.bing.net/th/id/R-C.d641eb2b1984277fe7eb301deaab2b8d?rik=awiunEDr9AFqTw&riu=http%3a%2f%2fpics.sc.chinaz.com%2ffiles%2fpic%2fpic9%2f201703%2fzzpic1687.jpg&ehk=1sYFoEaGFyJithPejoU7Br7is6GVRRA7ta9kIkTeizU%3d&risl=&pid=ImgRaw&r=0&sres=1&sresct=1",
        styles={
            "card": {
                "width": "450px",
                "height": "300px",
                "border-radius": "60px",
                "box-shadow": "0 0 10px rgba(234,0,0,0.5)",
                "background-color": "rgba(234, 0, 0, 0)"
            },
            "text": {
                "font-family": "serif",
            },
            "filter": {
                "background-color": "rgba(234, 0, 0, 0)"  # <- make the image not dimmed anymore
            }
        }
    )

    SecCol = st.columns([1,1,1])
    with SecCol[0]:
        st.header("噪声指纹图")
        with st.container(border=True):
            image = open(f"./res/trufor/_conf.png", 'rb').read()
            st.image(image, caption='Image',use_column_width=True)
    with SecCol[1]:
        st.header("RdBu_r图")
        with st.container(border=True):
            image = open(f"./res/trufor/_local.png", 'rb').read()
            st.image(image, caption='Image',use_column_width=True)
    with SecCol[2]:
        st.header("原图")
        with st.container(border=True):
            image = open(f"./upload/images/{uploaded_file.name}", 'rb').read()
            st.image(image, caption='Image',use_column_width=True)
    ThridCol = st.columns(1)
    with ThridCol[0]:
        with st.container(border=True):
            ResCol = st.columns([1,2,2,2,1])
            with ResCol[1]:
                st.header(f"伪造指数:")
            with ResCol[2]:
                html_text = f"<div style='background-color:#23ACF0; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>{score}</span></div>"
                st.write("")
                st.markdown(html_text, unsafe_allow_html=True)
            with ResCol[3]:
                if st.session_state.PhotoState == "real":
                    html_text = f"<div style='background-color:#42CF52; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>鉴定是real</span></div>"
                    st.write("")
                    st.markdown(html_text, unsafe_allow_html=True)
                if st.session_state.PhotoState == "doubt":
                    html_text = f"<div style='background-color:#F7E62F; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>鉴定是doubt</span></div>"
                    st.write("")
                    st.markdown(html_text, unsafe_allow_html=True)
                if st.session_state.PhotoState == "fake":
                    html_text = f"<div style='background-color:#F0275E; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>鉴定是fake</span></div>"
                    st.write("")
                    st.markdown(html_text, unsafe_allow_html=True)

    